<?php
declare (strict_types=1);

namespace app\course\logic\live\admin;

use app\common\exception\LogicException;
use app\course\model\live\admin\LiveSectionSyncLogs as LiveSectionSyncLogModel;

/**
 * Class LiveSectionSyncLogs
 *
 * @package app\course\logic\live\admin
 */
class LiveSectionSyncLogs extends LiveSectionSyncLogModel
{
    /**
     * 更新同步记录
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/11/11
     *
     * @param array $log
     * @return LiveSectionSyncLogs|array|int|\think\Model
     */
    public function updateOrCreatedLog(array $log)
    {
        $where = [
            'sync_room_id' => $log['room_id'],
            'sync_live_id' => $log['live_id']
        ];

        $data = $this->where($where)->findOrEmpty();
        if ($data->isEmpty()) {
            $data->sync_room_id = $log['room_id'];
            $data->sync_live_id = $log['live_id'];
        }

        $data->sync_total_count   = $log['total_count'];
        $data->sync_success_count = $log['success_count'];
        if (!$data->save()) {
            throw new LogicException('更新记录失败');
        }

        return $data;
    }

    /**
     * 是否已经同步过
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/11/11
     *
     * @param $roomId
     * @param $liveId
     * @return bool
     */
    public function isSynced($roomId, $liveId)
    {
        return (boolean)$this->where('sync_room_id', $roomId)->where('sync_live_id', $liveId)->value('id');
    }
}